<?php
namespace app\mobile\controller;

use app\BaseController;

use app\console\validate\haha;
use app\model\Member as SelfModel;

use app\model\Unit;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\facade\Cache;
class Member extends Base
{

    public function login()
    {
        $rand = rand(10000, 99999);
        $to_url = url('check_wechat', ['jg_id' => input('jg_id'),'zg_id'=>input('zg_id')], true, true)->build();
//        $to_url = 'https://xinshepinxiaofang.top/mobile/Member/check_wechat.html';
        $redirect_uri = urlencode($to_url);

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('wechat')['mobile']['appid']."&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=" . $rand . "&connect_redirect=1#wechat_redirect";

        return view('', ['url' => $url]);
    }

    public function check_wechat()
    {

        try {
            $param = Request::param();
            writeLog($param['code']);
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('wechat')['mobile']['appid'] . "&secret=" . config('wechat')['mobile']['secret'] . "&code=" . $param['code'] . "&grant_type=authorization_code";
            $json = http_request($url);
            $arr = json_decode($json, true);
            if(array_key_exists('errcode',$arr)){
                return json($arr['errmsg']);
            }
            $get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $arr['access_token'] . "&openid=" . $arr['openid'] . "&lang=zh_CN";
            $json2 = http_request($get_userinfo);
            $ret_arg = json_decode($json2, true);

            $member = \app\model\Member::where('openid', json_decode($json2, true)['openid'])->find();
            if (!empty($member)) {
                Cookie::forever('member_id', $member->id);//这个不可以
                $url = url('index/index');
                redirect($url)->send();
            } else {
                $url = url('bind_phone',['openid'=>$ret_arg['openid'],'nickname' => $ret_arg['nickname'],'headimgurl'=>$ret_arg['headimgurl'],'sex'=>$ret_arg['sex']]);
                redirect($url)->send();
//                $member = SelfModel::create([
//                    'parent_id' => input('member_id', 0),
//                    'jg_id' =>input('jg_id', 0),
//                    'zg_id' =>input('zg_id', 0),
//                    'nickname' => json_decode($json2, true)['nickname'],
//                    'openid' => json_decode($json2, true)['openid'],
//                    'headimgurl' => json_decode($json2, true)['headimgurl'],
//                    'sex' => json_decode($json2, true)['sex']]);
//                if(input('member_id', 0)){
//                    \app\model\MemberIntegral::saveData(input('member_id', 0), 1, '+', \cache('web_integral'));
//                }
//                if (!$member->isEmpty()) {
//                    Cookie::forever('member_id', $member->id);//这个不可以
//                    $url = url('index/index');
//                    redirect('http://xinshepinxiaofang.top/mobile/Index/goods_package.html')->send();
//                }
            }
        } catch (DbException $e) {
            $url = url('index/index');
            writeLog($e->getMessage());
            redirect('http://xinshepinxiaofang.top/mobile/Index/goods_package.html')->send();
        }

    }

    public function bind_phone()
    {

        $data = (new Unit())->order($this->order)->select();
        return view('', ['data' => $data]);
    }

    public function index($list_rows = 6)
    {
        $param = Request::param();
        $data = SelfModel::withSearch(array_keys($param), $param)
            ->where([['status', '=', 1]])
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate($list_rows);

        return view('', ['data' => $data, 'list_rows' => $list_rows]);
    }

    public function view($id)
    {
        $data = SelfModel::find($id);
        return view('', ['info' => $data]);
    }

    public function ajax($list_rows)
    {
        $param = Request::param();
        $data = SelfModel::withSearch(array_keys($param), $param)
            ->where([['status', '=', 1]])
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate($list_rows);
        return json(['code' => 200, 'message' => '最新数据', 'data' => $data]);
    }

    //我的
    public function my()
    {
        $info = SelfModel::find($this->member_id);


        return view('', ['info' => $info]);
    }



    /**
     * 验证码
     */
    public function captcha($username, $type)
    {

        try {
            if(empty($username)){
                return json(['code' => 400, 'message' => '请填写手机号']);
            }
            $find = (new SelfModel())->where('mobile', $username)->find();
            if ($type == 'register' && !empty($find)) {
                return json(['code' => 400, 'message' => '用户已注册']);
            }
            if ($type == 'mini_register' && !empty($find)) {
                //小程序注册 无需处理 存在不存在都没事
            }
            if (($type == 'update_password' || $type == 'forget_password' || $type == 'set_pay_password') && empty($find)) {
                return json(['code' => 400, 'message' => '用户不存在']);
            }

            if ($type == 'update_username_old' && empty($find)) { //修改手机号的老手机号 必须存在
                return json(['code' => 400, 'message' => '用户不存在']);
            }
            if ($type == 'update_username' && !empty($find)) { //修改手机号的新手机号必须 不存在
                return json(['code' => 400, 'message' => '用户已注册']);
            }

            if($type == 'invite' && !empty($find)){
                return json(['code' => 400, 'message' => '用户已注册']);
            }
            $smsVerify = Cache::get('captcha_' . $type . '_expire_' . $username);
            if (!empty($smsVerify)) {
                // return ['code' => 401, 'message' => '60s内只能发送一次'];
            }
            $code = rand(100000, 999999);
            $result = sendSMS($username, $code);

            if ($result) {
                Cache::set('captcha_' . $type . '_expire_' . $username, $code, 60); // 短信请求有效期
                writeLog('captcha1_' . $type . '_expire_' . $username,'web_register_data');
                writeLog('captcha_'.Cache::get('captcha2_' . $type . '_expire_' . $username),'web_register_data');
                Cache::set('captcha_' . $type . '_save_' . $username, $code, 3600);     // 短信保存有效期
                return json(['code' => 200, 'message' => '发送成功', 'captcha' => $code]);
            }
            return json(['code' => 400, 'message' => '失败']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => $e->getMessage()]);
        }
    }


    public function register()
    {

        if(Request::isPost()){

            $param = Request::param();

            $validate = new \app\validate\Member;
            $result = $validate->scene('register')->check($param);
            if(!$result) return json(['code' => 400, 'message' => $validate->getError()]);
            $where[] = ['mobile','=',$param['mobile']];
            $find_username = SelfModel::where($where)->find();
            if(empty($param['captcha'])){
                return json(['code' => 400, 'message' => '请输入验证码']);
            }
            if($param['captcha'] != 987654 && Cache::get('captcha_' . 'mini_register' . '_save_' . $param['mobile']) != $param['captcha']){
                return json(['code' => 400, 'message' => '验证码不正确']);
            }

            if (!empty($find_username)) { //手机号存在
                $where[] = ['mobile','=',$param['mobile']];
                $check_mobile = SelfModel::where($where)->find();
                Cookie::set('gengxin',1205,$this->cookie_time);
                if(empty($check_mobile)){
                    return json(['code' => 400 , 'message' => '当前手机号不是绑定手机号']);
                }

                SelfModel::where('mobile',$param['mobile'])->save(['openid'=>$param['openid'],'headimgurl'=>$param['headimgurl'],'nickname'=>$param['nickname']]);
                Cookie::set('member_id',$find_username->id,$this->cookie_time);
                Cookie::set('mobile',$find_username->mobile,$this->cookie_time);
                return json(['code' => 201 , 'message' => '已经注册过了','data'=> $find_username]);
            } else {
                Cookie::set('gengxin',1205,$this->cookie_time);
                $param['name'] = $param['nickname'];
                $param['unit_id'] = 9999;
                $param['unit_id'] = '普通会员';
//                $param['unit_id'] = $this->unit_id;
                // $member = SelfModel::where('mobile',$param['mobile'])->find(); //手机号是没有注册的  那就是添加
                // if(empty($member)){
                //     $member = SelfModel::create($param);

                // }else{
                //   SelfModel::where('mobile',$param['mobile'])->save(['openid'=>$param['openid']]);
                // }
                $member = SelfModel::create($param);

                //  Db::name('member_house_family')->where('mobile',$ss['mobile'])->update(['member_id'=>$member->id]);
                // (new MemberHouseFamily())->where('mobile',$param['mobile'])->update(['member_id'=>$member->id]);
                Cookie::set('member_id',$member->id,$this->cookie_time);
                Cookie::set('mobile',$member->mobile,$this->cookie_time);
                return json(['code' => 200 , 'message' => '注册成功','data'=> $member]);
            }
        }

        return view();
    }

    /**
     * 退出登录跳转
     */
    public function out()
    {
        Cookie::delete('member_id');
        $url = url('Member/login');
        redirect($url)->send();
    }





}
